package com.itheima.health.security;

import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.*;

/**
 * @author ：seanyang
 * @date ：Created in 2019/6/29
 * @description ：
 * @version: 1.0
 */
public class SecurityUserDetailsService implements UserDetailsService {

	// 模拟数据库的用户记录，如下User类是health_common中的自定义实体类User
	// 修改Role、Permission，为其增加不带参、带参构造方法，完成如下模拟过程
	private static Map<String, User> userDb = new HashMap();

	@Autowired
	private BCryptPasswordEncoder bCryptPasswordEncoder;

	static {
		BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
		User user1 = new User();
		user1.setUsername("admin");
		user1.setPassword(bCryptPasswordEncoder.encode("123"));
		// 用户权限与角色
		Role role1 = new Role("系统管理员","ROLE_ADMIN");
		Set<Permission> permissionSet = role1.getPermissions();
		permissionSet.add(new Permission("添加权限","add"));
		permissionSet.add(new Permission("删除权限","delete"));
		permissionSet.add(new Permission("更新权限","update"));
		permissionSet.add(new Permission("查询权限","find"));
		user1.getRoles().add(role1);
		userDb.put(user1.getUsername(),user1);

		User user2 = new User();
		user2.setUsername("zhangsan");
		user2.setPassword(bCryptPasswordEncoder.encode("456"));
		Role role2 = new Role("数据分析员","ROLE_DATA_READER");;
		role2.getPermissions().add(new Permission("查询权限","find"));
		user2.getRoles().add(role2);
		userDb.put(user2.getUsername(),user2);
	}
	/**
	 * 1. 根据用户标识（用户名），从数据库读取用户信息
	 * 2. 提取用户信息的角色与权限关键词信息
	 * 3. 把用户角色与权限关键词封装为List<GrantedAuthority>列表
	 * 4. 构建UserDetail对象（使用Security框架自动的User类封装），封装用户名、密码（必须是加密过的）及权限角色关键词列表
	 * @param username
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 根据用户标识（用户名），从数据库读取用户信息
		User user = userDb.get(username);

		if(user == null){
			return null;
		}
		System.out.println("loadUserByUsername: user:"+username+"pass:"+user.getPassword());

		//System.out.println("old:"+oldPassword+" authPassword:"+authPassword);
		/*
		String oldPassword = user.getPassword();
		String authPassword = bCryptPasswordEncoder.encode(oldPassword);
		System.out.println("old:"+oldPassword+" authPassword:"+authPassword);
		user.setPassword(authPassword);
		*/
		// 密码加密
		//String authPassword = "{noop}"+user.getPassword();
		// 提取用户信息的角色与权限关键词信息,并封装到GrantedAuthority列表
		List<GrantedAuthority> authorityList = new ArrayList<>();
		for(Role role:user.getRoles()){

			authorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
			for (Permission permission:role.getPermissions()){
				authorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
			}
		}

		UserDetails userDetails =
			new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorityList);
		return userDetails;
	}
}
